<template>
  <div class="main">
    <div class="edit-title">
      <input
        type="text"
        class="edit-title-input"
        placeholder="标题（必填）"
        :spellcheck="false"
        v-model="edit_title"
      />
      <div class="edit-title-lint"></div>
    </div>
    <div ref="edit_box">
      <editor-content :editor="editor" />
      <!-- <div style="width: 100%; height: 60px" ></div> -->
    </div>
    <div
      class="edit-bom"
      ref="bottom_fun"
      :style="{
        bottom: keyboard_height + 'px',
      }"
    >
      <div class="edit-fun">
        <div class="edit-fun-item">
          <!-- <div @click="editor.chain().focus().toggleBold().run()">加粗</div> -->
          <div class="edit-upload-img iconfont icon-tupian edit-iconfont">
            <input
              class="edit-upload-input"
              type="file"
              accept="image/*"
              @change="sel_img"
            />
          </div>
          <div
            class="iconfont icon-jiahao edit-iconfont"
            @click="add_b_video"
          ></div>
          <div
            class="iconfont icon-aite edit-iconfont"
            @click="on_delete"
          ></div>
          <div class="iconfont icon-7biaoqing-1 edit-iconfont"></div>
          <!-- <div @click="reset">重置</div> -->
        </div>
        <div class="edit-save" @click="edit_save">保存</div>
      </div>
      <!-- <div style="width: 100%; height: 373px; background: red"></div> -->
    </div>
  </div>
</template>

<script setup>
import { Editor, EditorContent } from "@tiptap/vue-3";
import StarterKit from "@tiptap/starter-kit";
import { ref, watch, onBeforeUnmount, onMounted } from "vue";
import { useRoute } from "vue-router";
import Image from "@tiptap/extension-image";
import axios from "../../utils/request";
import Placeholder from "@tiptap/extension-placeholder";
import DraggableItem from "../../assets/js/edit-render-view";
import Iframe from "../../assets/js/edit-render-iframe.ts";
import VConsole from "vconsole";
import utils from "../../assets/js/utils";
const vConsole = new VConsole();
let content = ref("");
let edit_title = ref("");
let keyboard_height = ref(0);
let bottom_fun = ref(HTMLDivElement);
let edit_box = ref(HTMLDivElement);
let edit_img = ref([]);
let edit_text = ref(""); //编辑器的文字
const route = useRoute();
let updata_edit = ref(""); //修改进来的编辑器
let editor = new Editor({
  content: updata_edit.value,
  extensions: [
    StarterKit,
    DraggableItem,
    Iframe,
    Placeholder.configure({
      placeholder: "请尽情的发挥吧...",
    }),

    Image.configure({
      allowBase64: true,
    }),
  ],
  onUpdate: ({ editor }) => {
    content.value = editor.getHTML();
    let text_json = editor.getJSON();
    console.log("1112",content.value)
    let edit_format_text = "";
    edit_text.value = editor.getHTML().replace(/<img.*?src=.*?>/g, "[图片]").replace(/<iframe(([\s\S])*?)<\/iframe>/ig,'[视频]').replace(/<[^>]+>/g,'')
    console.log("文字",edit_text.value)

    // text_json.content.forEach((item) => {
    //   if (item?.content && item.type == "paragraph") {
    //     item.content.forEach((doc_text) => {
    //       switch (doc_text.type) {
    //         case "text":
    //           edit_format_text += doc_text.text;
    //           break;
    //         default:
    //           edit_format_text += "";
    //           break;
    //       }
    //     });
    //   } else if (item?.attrs && item.type == "iframe") {
    //     edit_format_text += "[视频]";
    //   } else if (item?.attrs && item.type == "image") {
    //     edit_format_text += "[图片]";
    //   } else {
    //     edit_format_text += " ";
    //   }
    // });
    edit_text.value = edit_format_text;
  },
  onFocus: () => {},
  onBlur: () => {},
});

// 添加b站视频
const add_b_video = () => {
  const bv_id = window.prompt("输入bv号");
  let url = `https://player.bilibili.com/player.html?bvid=${bv_id}&page=1`;
  if (bv_id) {
    editor.chain().focus().setIframe({ src: url }).run();
    // editor.commands.insertContent('11');
  }
};

const reset = () => {
  let aa = `${content.value}`;
  console.log(aa);
  //   editor.commands.setContent(aa,true);
};

const on_delete = () => {
  editor.commands.deleteNode("paragraph");
};

//添加图片
const addImage = function (e) {
  const url = window.prompt("URL");
  console.log(url);
  if (url) {
    editor.chain().focus().setImage({ src: url }).run();
  }
};

const get_keyboard_height = () => {
  // console.log("win", window.innerHeight);
  // console.log("vis", visualViewport.height);
  keyboard_height.value = visualViewport.height;
  // window.addEventListener('scroll',()=>{
  //   keyboard_height.value = keyboard_height.value - window.scrollY
  //   console.log(keyboard_height.value)
  // })
};

const ban_scroll = (e) => {
  e.preventDefault();
};

onMounted((e) => {
  let diary_id = route.query.diary_id || null;
  if (diary_id) {
    get_diary_content(diary_id);
  }
  console.log(route.query);
  // console.log("当前页面的高度", document.documentElement.clientHeight);
  let monitorKeyboard = new utils.Monitorkey();
  monitorKeyboard.onStart();
  monitorKeyboard.onShow((e) => {
    // visualViewport.addEventListener("resize", get_keyboard_height);
    visualViewport.addEventListener("resize", () => {
      setTimeout(() => {
        bottom_fun.value.scrollIntoViewIfNeeded(false);
        // console.log( bottom_fun.value.scrollIntoView(false))
        //页面移动到dom节点
        //   document.body.scrollTop = document.body.scrollHeight
        //     console.log(document.body.scrollHeight)
      }, 300);
    });
    // document.body.addEventListener('touchmove',ban_scroll, { passive: false })
  });

  //监听键盘收起的事件
  monitorKeyboard.onHidden(() => {
    keyboard_height.value = 0;
    document.activeElement.scrollIntoView(true);
    // document.body.removeEventListener("touchmove", ban_scroll, {
    //   passive: false,
    // });
    visualViewport.removeEventListener("resize", get_keyboard_height);
  });
});

const get_diary_content = async (diary_id) => {
  try {
    let response = await axios({
      url: "/edit/diary/detail",
      params: {
        diary_id,
      },
    });
    console.log(response);
  } catch (e) {}
};

const sel_img = async (e) => {
  const body = new FormData();
  let file = e.target.files[0];
  if (file) {
    body.append("file", file);
    try {
      const response = await axios({
        method: "post",
        url: "/postFile",
        data: body,
      });
      edit_img.value.push(response.url);
      console.log(response.url);
      editor.chain().focus().setImage({ src: response.url }).run();
    } catch (e) {
      console.log(e);
    }
  } else {
    alert("请选择文件！");
  }
};

const edit_save = async () => {
  try {
    const response = await axios({
      method: "post",
      url: "/edit/save",
      data: {
        content: content.value,
        edit_img: edit_img.value,
        text: edit_text.value,
        title: edit_title.value,
      },
    });
    if (response.code == 200) {
      console.log(response);
    }
  } catch (e) {}
};

onBeforeUnmount(() => {
  editor.destroy();
});
</script>

<style lang="scss">
@import "./edit.scss";
</style>
